import cv2
import numpy as np
def draw_hist(image,color):
    hist=cv2.calcHist(
        [image],
        [0],
        None,
        [256],
        [0,255]
    )
    min_val,max_val,min_loc,max_loc=cv2.minMaxLoc(hist)
    hist_img=np.zeros([256,256,3],np.uint8)
    hpt=int(256*0.9)
    for h in range(256):
        intensity=int(hpt*hist[h]/max_val)
        cv2.line(
            hist_img,
            (h,256),
            (h,256-intensity),
            color
        )
    return hist_img
if __name__=='__main__':
    image=cv2.imread("C:\\Users\\20436\Desktop\yaogan.jpg")
    image_np_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 3. 绘制直方图
    hist_image = draw_hist(image_np_gray, (0, 0, 255))

    # 4. 直方图均衡化
    clahe = cv2.createCLAHE(
        clipLimit=10,
        tileGridSize=(5, 5)
    )

    equ_hist_image_np = clahe.apply(image_np_gray)

    # 5. 绘制直方图
    equ_hist_image = draw_hist(equ_hist_image_np, (0, 255, 255))

    # 6. 图片输出
    # cv2.imshow('hist_image', hist_image)
    # cv2.imshow('equ_hist_image', equ_hist_image)
    # cv2.imshow('equ_hist_image_np', equ_hist_image_np)
    cv2.imwrite('equ_hist_image_np.jpg', equ_hist_image_np)
    cv2.waitKey(0)